<?

//require_once(dirname(__FILE__) . '/../abstract/db.php');

class bf_db_sqlite2 extends bf_db {

	private $conn;
	protected $err_msg;

	public function __construct($options = array()) {
		$opts = array_merge(array(
			'database' => 'database.sqlite',
			'log' => dirname(__FILE__) . '/../../../logs/db-sqlite2-' . date('Y-m-d') . '.log',
			'logging' => 1,
		), $options);
		$this->err_msg = '';
		parent::__construct($opts);
	}

	public function escape($str) {
		return sqlite_escape_string($str);
	}

	public function connect() {
		$this->conn = @sqlite_open(
			$this->opts['database']
		);
		if (!$this->conn) {
			$this->err_msg = "Couldn't open/create database file \"{$this->opts['database']}\".\n";
			$this->log_error();
		}
	}

	public function disconnect() {
		if ($this->conn)
			@sqlite_close($this->conn);
	}

	public function is_connected() {
		return ($this->conn ? true : false);
	}

	public function get_true() {
		return '1';
	}

	public function get_false() {
		return '0';
	}

	public function is_true($value) {
		return preg_match('/^(t|1)/i', "$value");
	}

	public function is_false($value) {
		return preg_match('/^(f|0)/i', "$value");
	}

	protected function make_query($sql, $params = array()) {
		$this->err_msg = '';
		$this->params = $params;
		$processed_sql = preg_replace_callback("/'(?:\\'|.)*?'|\\$(\\d+)/", array($this, 'get_param'), $sql);
		$this->params = null;
		if ($this->opts['logging'] > 1)
			$this->log_append("SQL: $sql\nPARAMS: ".join(', ', $params)."\nSQL TO EXECUTE: $processed_sql\n");
		if (!($res = @sqlite_query($this->conn, $processed_sql, SQLITE_BOTH, $this->err_msg)))
			$this->log_error();
		return $res;
	}

	public function fetch_all($res, $params = array()) {
		if (!($rows = @sqlite_fetch_all($res)))
			$rows = array();
		return $rows;
	}

	public function fetch_row($res) {
		return @sqlite_fetch_array($res, SQLITE_ASSOC);
	}

	public function fetch_column($res, $column = false) {
		$row = ($column ? $this->fetch_row($res) : @sqlite_fetch_array($res, SQLITE_NUM));
		return ($column ? @$row[$column] : @$row[0]);
	}

	public function is_error() {
		return ($this->err_msg ? true : false);
	}

	public function get_error_text() {
		return $this->err_msg;
	}

	public function get_debug_text() {
		return '';
	}

	public function start() {
		return $this->query('begin transaction');
	}

	public function commit() {
		return $this->query('commit transaction');
	}

	public function rollback() {
		return $this->query('rollback transaction');
	}

	private function get_param($matches) {
		if (preg_match('/^\$/', $matches[0])) {
			$param = $this->params[intval($matches[1]) - 1];
			if ($param === null) {
				return 'NULL';
			}
			if (is_int($param)) {
				return $param;
			}
			return "'" . $this->escape($param) . "'";
		} else {
			return $matches[0];
		}
	}
}

?>